package com.happy.xiao.common.utils;

import java.util.Collections;
import java.util.List;

/**
 * 结果分页工具类
 *
 * @author 方承刚
 * @create 2018/9/14
 * @since 1.0.0
 */
public class PageUtil<T> {
    /**
     * 原集合
     */
    private List<T> data;

    /**
     * 当前页
     */
    private int pageNum;

    /**
     * 每页条数
     */
    private int pageSize;

    /**
     * 总页数
     */
    private int totalPage = 0;

    /**
     * 总数据条数
     */
    private int totalElements = 0;

    /**
     * 得到对象
     */
    public PageUtil listToPage(List<T> data, int pageNum, int pageSize) {
        PageUtil page = new PageUtil<>();
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        if (data == null || data.isEmpty()) {
            return page;
        }
        page.setData(convertData(data, pageNum, pageSize));
        page.setTotalElements(data.size());
        page.setTotalPage((page.getTotalElements() + pageSize - 1) / pageSize);
        return page;
    }

    /**
     * 得到分页后的数据
     */
    public List<T> convertData(List<T> data, int nowPage, int pageSize) {
       /* int fromIndex = (nowPage) * pageSize;
        if (fromIndex >= data.size()) {
            return Collections.emptyList();//空数组
        }
        if(fromIndex<0){
            return Collections.emptyList();//空数组
        }
        int toIndex = (nowPage + 1) * pageSize;
        if (toIndex >= data.size()) {
            toIndex = data.size();
        }*/

        int fromIndex = (nowPage - 1) * pageSize;
        if (fromIndex >= data.size()) {
            return Collections.emptyList();//空数组
        }
        if (fromIndex < 0) {
            return Collections.emptyList();//空数组
        }
        int toIndex = nowPage * pageSize;
        if (toIndex >= data.size()) {
            toIndex = data.size();
        }
        return data.subList(fromIndex, toIndex);
    }


    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalElements() {
        return totalElements;
    }

    public void setTotalElements(int totalElements) {
        this.totalElements = totalElements;
    }
}